<?php 
class Scan extends CI_Controller {
	
	function scan()
	{
		parent::__construct();
		$this->load->library('session');
		$this->load->library('form_validation');
		$this->load->library('encrypt');
		$this->load->library('fpdf');
		$this->load->library('enc');
                $this->load->model('mmaster');
                $this->load->model('mglobal');
				$this->load->model('mscan');
		$this->is_logged_in();
		#$this->mjadwal->saveLog();
		$this->load->helper('url');
		$this->load->helper('file');
	}
	
	function is_logged_in()
	{
		$is_logged_in = $this->session->userdata('is_logged_in');
		if(!isset($is_logged_in) || $is_logged_in != true)
		{
			redirect(base_url() .'index.php/login');
		}		
	}
	
	//function index($act="",$page="")
	function index()
	{
		$data['template'] 	= "shell/smooth";
		$data['main_view']  = 'f-scan';
		$this->load->view($data['template'],$data);
	}

	//proses pembuatan scan bring in product form
		function newscan(){
			$data['template'] = "shell/smooth";
			// $data['main_view'] = "f-scan-create";
			$data['main_view'] = "trans/scan_create";

			$cluster_id = $this->mglobal->user_cluster($this->session->userdata('username'));
			$data['sales_id'] = $this->mglobal->get_sales($cluster_id, array(8,9,31,32,35));

    $teritori = explode('>', $this->mglobal->getTerritoryPath());
    $data['region'] = $teritori[0];
    $data['cluster'] = $teritori[1];
	
		$iccid      = $this->input->post('iccid');
		$sales_name = $this->input->post("sales_id");

    $this->form_validation->set_rules('scan_date', 'scan date', 'required');
    $this->form_validation->set_rules('sales_id', 'sales id', 'required');
    $this->form_validation->set_rules('iccid[]', 'iccid', 'required');
        
		if ($this->form_validation->run() != false) {

			$duplicate_iccid = array_count_values($iccid);	// Returns ['iccid_0']=>counts, [iccid_1]=>counts
			$unique_iccid = array_unique($iccid); 			// Returns [0]=>"iccid_0", [1]=>"iccid_1"
			$new_iccid = array(); $dup_iccid = array();

			foreach ($unique_iccid as $key) {				// $key become unique_iccid value: iccid_0, iccid_1
				if($duplicate_iccid[$key] == 1) {			// if the count equal to 1, create new array, the array is now unique
					$new_iccid[] = $key;
				}
				else {
					$dup_iccid[] = $key;					// if the count greater then to 1, create new array contains unique iccid above.
				}
			}

			$iccidsama='';
			foreach ($dup_iccid as $a){
				$iccidsama.=$a.', ';
			}

			// Validate each unique iccids and return as new array named valid_iccid
			$valid_iccid = array();
			// var_dump($new_iccid);
			$i = 0; 
			foreach ($new_iccid as $key) {
				$valid_iccid[] = $this->validate_item($key, $sales_name);
				if ($valid_iccid[$i] == null)
					{	unset($valid_iccid[$i]) ;}
				$i++;
			}
			// var_dump($valid_iccid); die();
			if (count($valid_iccid) != 0 ) {	// if array is not null, save transactions
				$this->db->trans_begin();

				// $lastSid = $this->mscan->saveScan();
				$scan_in_id = $this->mscan->save_scan_in($sales_name);
			
				foreach ($valid_iccid as $item) {
					$this->mscan->save_scan_in_detail($scan_in_id, $item); 
				}

				if ($this->db->trans_status() === FALSE)
				{
					$this->db->trans_rollback();
				   $this->session->set_flashdata('message', 'Tidak ada item yang valid, ulangi input ICCID');
				   redirect(base_url() . "index.php/scan/newscan");
				}
				else
				{
					$this->db->trans_commit();
					
					if (count($dup_iccid) != 0) { $message = "Data berhasil disimpan dengan nomor transaksi $scan_in_id, terdapat duplikat ICCID: $iccidsama" ; }
					else {$message = "Data berhasil disimpan dengan nomor transaksi $scan_in_id" ; }
					$this->session->set_flashdata('message', $message);
					redirect(base_url() . "index.php/scan ");
				}
			}

		}
		
        $this->load->view($data['template'], $data);
    }
		
	function validate_item($iccid, $sales_id) {
		$item = $this->mscan->validate_item($iccid, $sales_id);
		if ($item == 1) { return $iccid; }
	}

	public function ajaxValidate() {
		$sales_id = $this->input->post('sales_id');
		$iccid    = $this->input->post('iccid');
		$data = $this->mscan->ajaxValidate($sales_id, $iccid);
		echo json_encode($data);
	}

	/**
	 * Scan In Datatables
	 * @return JSON
	 */
	public function dataList()
	{

    $cluster_id = $this->mglobal->user_cluster($this->session->userdata('username'));
    $aColumns = array('ss.scan_in_id', 'ss.scan_date', 'ss.user_id', 'uu.user_name', 'ss.acess_via');
    $sIndexColumn = "ss.scan_in_id";
    $sTable = "t_trx_scan_in ss join t_mtr_user uu on uu.user_id = ss.user_id";

    $sLimit = "";
    if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
	    { $sLimit = "LIMIT ".intval( $_GET['iDisplayLength'] )." OFFSET ". intval( $_GET['iDisplayStart'] ); }
     
    if ( isset( $_GET['iSortCol_0'] ) )
    {
        $sOrder = "ORDER BY  ";
        for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
        {
          if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
          { $sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]." ".($_GET['sSortDir_'.$i]==='desc' ? 'asc' : 'desc').", "; }
        }
         
        $sOrder = substr_replace( $sOrder, "", -2 );
        if ( $sOrder == "ORDER BY" )
	        { $sOrder = ""; }
    }
     
    $sWhere = "WHERE f_get_cluster(ss.user_id) = $cluster_id ";
    $sWhere .= "AND date_part('month', ss.created_on) = date_part('month', now())";
		$sWhere .= "AND date_part('month', ss.created_on) = date_part('month', now())";
    if ( $_GET['sSearch'] != "" )
    {
        $sWhere = "WHERE f_get_cluster(ss.user_id) = $cluster_id ";
        $sWhere .= "AND date_part('month', ss.created_on) = date_part('month', now())";
		    $sWhere .= "AND date_part('month', ss.created_on) = date_part('month', now()) AND (";
        // $sWhere = "WHERE f_get_cluster(ss.user_id) = $cluster_id AND (";
        for ( $i=0 ; $i<count($aColumns) ; $i++ )
        {
          if ( $_GET['bSearchable_'.$i] == "true" )
          { $sWhere .= $aColumns[$i]." ILIKE '%".$this->db->escape_str( $_GET['sSearch'] )."%' OR "; }
        }
        $sWhere = substr_replace( $sWhere, "", -3 );
        $sWhere .= ")";
    }
     
    /* Individual column filtering */
    for ( $i=0 ; $i<count($aColumns) ; $i++ )
    {
      if ( $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )
      {
        if ( $sWhere == "" )
          { $sWhere = "WHERE f_get_cluster(ss.user_id) = $cluster_id"; }
        else
          { $sWhere .= " AND "; }
        $sWhere .= $aColumns[$i]." ILIKE '%".$this->db->escape_str($_GET['sSearch_'.$i])."%' ";
      }
    }
     
     
    $sQuery = "
        SELECT ".str_replace(" , ", " ", implode(", ", $aColumns))."
        FROM   $sTable
        $sWhere
        $sOrder
        $sLimit
    ";
    $rResult = $this->db->query($sQuery);
     
    $sQuery = "
			SELECT count(*) AS numrows
      FROM   $sTable
			WHERE f_get_cluster(ss.user_id) = $cluster_id 
			AND date_part('month', ss.created_on) = date_part('month', now())
			AND date_part('month', ss.created_on) = date_part('month', now())
    ";
    $rResultTotal = $this->db->query($sQuery)->row(); 
    $iTotal       = $rResultTotal->numrows;
     
    if ( $sWhere != "" )
    {
      $sQuery = "
				SELECT count(*) AS numrows
        FROM   $sTable
        $sWhere " . " 
        AND date_part('month', ss.created_on) = date_part('month', now())
        AND date_part('year', ss.created_on) = date_part('year', now())
      ";
      $rResultFilterTotal = $this->db->query($sQuery)->row(); 
      $iFilteredTotal     = $rResultTotal->numrows;
    }
    else
    { $iFilteredTotal = $iTotal; }
     
    $output = array(
        "sEcho" => intval($_GET['sEcho']),
        "iTotalRecords" => $iTotal,
        "iTotalDisplayRecords" => $iFilteredTotal,
        "aaData" => array()
    );

    foreach ($rResult->result_array() as $aRow  )
    {
      $row = array();
      for ( $i=0 ; $i<count($aColumns) ; $i++ )
      {
        if ( $aColumns[$i] != null )
        {
        
          $colName = explode('.', $aColumns[$i]);
          $colName = $colName[1];
          
          $row[] = $aRow[ $colName ];
        }
      }
      $output['aaData'][] = $row;
    }

    // while ( $aRow = pg_fetch_array($rResult, null, PGSQL_ASSOC) )
    // {
    //     $row = array();
    //     for ( $i=0 ; $i<count($aColumns) ; $i++ )
    //     {
    //         if ( $aColumns[$i] == "version" )
    //         {
    //             /* Special output formatting for 'version' column */
    //             $row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];
    //         }
    //         else if ( $aColumns[$i] != ' ' )
    //         {
    //             /* General output */
    //             $row[] = $aRow[ $aColumns[$i] ];
    //         }
    //     }
    //     $output['aaData'][] = $row;
    // }
     
    echo json_encode( $output );
     
	}

    // untuk manage data yang ditampilkan pada grid view
    public function read() {
		//echo json_encode( $this->mscan->getAllScanin() );
		//edited by Alfin Akhret
    $cluster_id = $this->mglobal->user_cluster($this->session->userdata("username"));

		if($this->session->userdata('is_self_service') == 1)
		{
			$result = $this->mscan->getAllScaninCurrentUser();
		}
		else
		{
			$result = $this->mscan->getAllScanin($cluster_id);
		}

        //encode
       for($i=0;$i<count($result['aaData']);$i++)
       {
    			// $result[$i]->scan_in_id = $this->enc->fogit($result[$i]->scan_in_id);
    			$result['aaData'][$i][2] = $this->enc->fogit($result['aaData'][$i][2]); //edited by: alfin akhret
    	 }
        
         //penambahan nomor statis untuk grid SSP
        $start=$_GET['iDisplayStart'];
        $result['iDisplayStart']=$start;
        
        echo json_encode($result);
	}
	
	function defoger()
    {
        $result = $this->enc->defog($this->input->post('str'));
        echo $result;  
    }
	
	//process posted form data (the requested items like province)
    function load_scan($iccid, $sales_id){
       
		//anggwa@gmail.com 20120508
		$iccidExplode = explode("#", $iccid);
		$salesIdExplode = explode(" ", $sales_id);
         $data['test'] = $this->mscan->getScan($iccidExplode[0], trim($salesIdExplode[0])); //Search DB
        //$data['test'] = $this->mscan->getScan($iccid, $sales_id); //Search DB
        
        if('IS_AJAX')
        {
            echo json_encode($data['test']);
        }
    }
	
	
	//ambil daftar iccid untuk ditampilkan pada textbox autocomplete, melalui method getRelatedIccid di model mscan
	function getRelatedIccid($salesId, $term){
        
        $data['relatedIccid'] = $this->mscan->getRelatedIccid($salesId, $term); //Search DB
        
        if('IS_AJAX')
        {
            echo json_encode($data['relatedIccid']);
        }
    }
	
	// Fungsi ini untuk mengukur kredit limit, dipanggil oleh f_scan_create dengan AJAX
	function getCurrentLimit($sales_id){
	//	$sales_id = $this->uri->segment(4);
		$data['currentSalesLimit'] = $this->mscan->getCurrentLimit($sales_id);

		if('IS_AJAX')
		{
			echo json_encode($data['currentSalesLimit']);
		}
	}

	// // Fungsi ini untuk mendapatkan batasan limit maksimal, dipanggil oleh f_scan_create dengan AJAX
	function getCreditLimit($sales_id){
		$data = $this->mscan->getCreditLimit($sales_id);
		echo $data;
	}

	function getLimitMinMax($sales_id) {
		$c = $this->mscan->getCurrentLimit($sales_id);
		$m = $this->mscan->getCreditLimit($sales_id);

		echo $c.':'.$m;

	}


	//concate id pada row table tertentu untuk keperluan view
	public function concateId($id)
	{
		$tempId = "" . $id;
		if (strlen($tempId) < 8)
		{
			for($ii=strlen($tempId); $ii<8; $ii++)
			{
				$tempId = '0' . $tempId;
			}
		}
		return $tempId;
	}
	
	public function detail($sIdEncoded)
	{
		$scanId            = $this->enc->defog($sIdEncoded); 
		$data['detail']    = $this->mscan->scan_details($scanId);
		$data['template']  = "shell/smooth";
		$data['main_view'] = 'trans/scan_detail';
		$this->load->view($data['template'],$data);
		// print_r($data);
	}
	//proses data untuk halaman detail
	function getDetail($id1='', $id2='')
	{
		//$scan_id = $id1;
		$scan_id = $this->enc->defog($id2); 
		
		$temp = $this->mscan->getById($scan_id);
		$sales_id = $temp->user_id;
		
		// $temp = "";
		// $temp = $this->mscan->getClusterName($this->session->userdata('username'));
		// $data['ter_name'] 	= $temp[0]['territory_name'];
		// $ter_id 			= $temp[0]['territory_id'];
		
		
		$temp = $this->mscan->getClusterName($this->session->userdata('username'));	
		if (count($temp) > 0)
			foreach($temp as $result)
			{
				$data['ter_name'] = $result['territory_name'];
				$ter_id = $result['territory_id'];
			}
		else
		{
			$data['ter_name'] = "No Data";
			$ter_id = "No Data";
		}
		$list = $this->pdfAndDetail($scan_id, $ter_id);
			$data['strId'] = $list[0];
			$data['scan_in'] = $list[2];
			$data['sales_name'] = $list[3];
			$data['scan_in_detail'] = $list[4];

		$data['record'] = $this->mscan->getIccidByScanId($scan_id);

		$data['template'] 	= "shell/smooth";
		$data['main_view']  = 'f-scan-detail';
		$this->load->view($data['template'],$data);
			
	}
	

	function tet($scan_id) {
		$test = $this->mscan->getPdfDetails($scan_id);
		foreach ($test as $key) {
			echo $key->item_name;
		}
	}
	//proses data untuk men-generate file pdf dan detail view
	function pdfAndDetail($scan_id, $ter_id)
	{
		$list = array();
		
		$list[0] = $this->concateId($scan_id);
		
		$list[2] = $this->mscan->getById($scan_id);
		
		$this->db->select('user_name');
		$this->db->where('user_id', $list[2]->user_id);
		$q = $this->db->get('t_mtr_user');
		$list[3] = $q->result_array();		
		
		$this->db->select('*');
		$this->db->where('scan_in_id', $scan_id);
		$q = $this->db->get('t_trx_scan_in_detail');
		$list[4] = $q->result_array();
		
		for($ii=0;$ii<count($list[4]);$ii++)
		{
			$list[$ii+5] = $this->mscan->getPdfDetails($scan_id);
		}
		
		return $list;
	
	}

	//proses data untuk men-generate file pdf
	function topdf($id1='', $id2='')
	{
	
		//$scan_id = $id1;
		$scan_id = $this->enc->defog($id1); 
		
		$temp = $this->mscan->getById($scan_id);
		$sales_id = $temp->user_id;		
		
		$temp = $this->mscan->getClusterName($this->session->userdata('username'));	
		if (count($temp) > 0)
			foreach($temp as $result)
			{
				$ter_name = $result['territory_name'];
				$ter_id  = $result['territory_id'];
			}
		else
		{
			$ter_name = "No Data";
			$ter_id  = "No Data";
		}
		

		$list 		= $this->pdfAndDetail($scan_id, $ter_id);
		$strId 		= $list[0];
		$scan_in 	= $list[2];
		$sales_name = $list[3];
		// $scan_in_detail = $list[4];
		$scan_in_detail = $this->mscan->getPdfDetails($scan_id);
		
		// for($ii=0;$ii<count($list[4]);$ii++)	
		// {
		// 	$itemDetail[$ii] = $list[5+$ii];
		// }
		
		//begin configuration
		$textColour = array( 0, 0, 0 );
		$headerColour = array( 100, 100, 100 );
		$tableHeaderTopTextColour = array( 0, 0, 0 );
		$tableHeaderTopFillColour = array( 250, 250, 250 );
		$tableHeaderTopProductTextColour = array( 0, 0, 0 );
		$tableHeaderTopProductFillColour = array( 143, 173, 204 );
		$tableHeaderLeftTextColour = array( 99, 42, 57 );
		$tableHeaderLeftFillColour = array( 184, 207, 229 );
		$tableBorderColour = array( 50, 50, 50 );
		$tableRowFillColour = array( 255, 255, 255 );
		

		$chartColours = array(
						  array( 255, 100, 100 ),
						  array( 100, 255, 100 ),
						  array( 100, 100, 255 ),
						  array( 255, 255, 100 ),
						);

		$data = array(
				  array( 9940, 10100, 9490, 11730 ),
				  array( 19310, 21140, 20560, 22590 ),
				  array( 25110, 26260, 25210, 28370 ),
				  array( 27650, 24550, 30040, 31980 ),
				);
		// End configuration
		
		
		$this->load->helper('path');

		$font_directory = './fpdf_fonts/';
		set_realpath($font_directory);
		define('FPDF_FONTPATH',$font_directory);
		
		$this->fpdf->Open();
		$this->fpdf->AddPage();
		$this->fpdf->SetAutoPageBreak(true, 5);
		$this->fpdf->SetMargins(10, 20, 20);
		$this->fpdf->AliasNbPages();
		
		
		//header
		//$this->fpdf->Image(BASEPATH.'../file/images/logo_smartfren.png',10,3,50,0,'');	
		$this->fpdf->Image(FCPATH.'file/images/logo_smartfren.png',10,3,50,0,'');			
		$this->fpdf->SetFont('Arial','B',12);
		$this->fpdf->Cell(180,-5,"Delivery Notes",0,1,'R');	
		$this->fpdf->Ln( 10 );
		$this->fpdf->SetFont('Arial','B',8);
		$this->fpdf->Cell(190,0,"(Pengambilan Barang dari Cluster)",0,1,'R');		
		$this->fpdf->Line(10, 20, 200, 20);
		
		//table
		$this->fpdf->SetDrawColor( $tableBorderColour[0], $tableBorderColour[1], $tableBorderColour[2] );
		
		//Cluster Information		
		$this->fpdf->Ln(5);
		$this->fpdf->SetFont('Arial','B',16);		
		$this->fpdf->Write(19, $ter_name);
		$this->fpdf->Ln( 6 );
		
		
		// Date and receipt no
		$this->fpdf->Ln(15);
		$this->fpdf->SetXY(130, 42);
		$this->fpdf->SetFont('Arial','B',8);
		$this->fpdf->SetTextColor( $tableHeaderTopTextColour[0], $tableHeaderTopTextColour[1], $tableHeaderTopTextColour[2] );
		$this->fpdf->SetFillColor( $tableHeaderTopFillColour[0], $tableHeaderTopFillColour[1], $tableHeaderTopFillColour[2] );
		$this->fpdf->Cell( 30, 8, "Tanggal", 1, 0, 'C', true );
		$this->fpdf->Cell( 40, 8, "No. Scan In", 1, 0, 'C', true );		
		$this->fpdf->SetXY(130, 50);
		
		$fill = false;
		$row = 0;		
		$this->fpdf->SetTextColor( $textColour[0], $textColour[1], $textColour[2] );
		$this->fpdf->SetFillColor( $tableRowFillColour[0], $tableRowFillColour[1], $tableRowFillColour[2] );
		$this->fpdf->SetFont( 'Arial', '', 8 );		
		$this->fpdf->Cell( 30, 8, date("d-m-Y", strtotime($scan_in->scan_date)).' '.$scan_in->data_timestamp, 1, 0, 'C', $fill );
		$this->fpdf->SetFont( 'Arial', 'B', 8 );		
		$this->fpdf->Cell( 40, 8, $strId, 1, 0, 'C', $fill );
					
	
		$this->fpdf->Ln( 20 );
			
		// Order Information
		$this->fpdf->SetXY(10, 42);
		$this->fpdf->SetTextColor( $tableHeaderTopTextColour[0], $tableHeaderTopTextColour[1], $tableHeaderTopTextColour[2] );
		$this->fpdf->SetFillColor( $tableHeaderTopFillColour[0], $tableHeaderTopFillColour[1], $tableHeaderTopFillColour[2] );
		$this->fpdf->SetFont( 'Arial', 'B', 8 );
		$this->fpdf->Cell( 25, 8, "Sales ID", 1, 0, 'C', true );
		$this->fpdf->Cell( 45, 8, "Nama Sales", 1, 0, 'C', true );		
		$this->fpdf->Ln( 8 );
		$this->fpdf->SetFont( 'Arial', '', 8 );
		$this->fpdf->SetTextColor( $textColour[0], $textColour[1], $textColour[2] );
		$this->fpdf->SetFillColor( $tableRowFillColour[0], $tableRowFillColour[1], $tableRowFillColour[2] );
		$this->fpdf->Cell( 25, 8, $scan_in->user_id, 1, 0, 'C', $fill );
		$this->fpdf->Cell( 45, 8, $sales_name[0]['user_name'], 1, 0, 'C', $fill );		

		
		// Order Information
		$this->fpdf->Ln( 20 );
		$this->fpdf->SetTextColor( $tableHeaderTopTextColour[0], $tableHeaderTopTextColour[1], $tableHeaderTopTextColour[2] );
		$this->fpdf->SetFillColor( $tableHeaderTopFillColour[0], $tableHeaderTopFillColour[1], $tableHeaderTopFillColour[2] );
		$this->fpdf->SetFont( 'Arial', 'B', 8 );
		$this->fpdf->Cell( 30, 8, "Kode Barang", 1, 0, 'C', true );
		$this->fpdf->Cell( 15, 8, "Jumlah", 1, 0, 'C', true );		
		$this->fpdf->Cell( 70, 8, "Nama Barang", 1, 0, 'C', true );		
		$this->fpdf->Cell( 25, 8, "Item Group", 1, 0, 'C', true );		
		$this->fpdf->Cell( 25, 8, "Harga (Rp.)", 1, 0, 'C', true );			
		$this->fpdf->Cell( 25, 8, "Subtotal (Rp.)", 1, 0, 'C', true );			
		$this->fpdf->Ln( 1 );
		
		$price = 0;
		$subtotal = 0;
		$subname = "";

		$this->fpdf->SetFont( 'Arial', '', 7 );
		$this->fpdf->Ln( 7 );
		$this->fpdf->SetTextColor( $textColour[0], $textColour[1], $textColour[2] );
		$this->fpdf->SetFillColor( $tableRowFillColour[0], $tableRowFillColour[1], $tableRowFillColour[2] );

		foreach ($scan_in_detail as $detail) {
			$jumlah = $detail->jumlah;
			$harga = $detail->harga;

			$this->fpdf->Cell( 30, 7, $detail->item_code, 1, 0, 'L', $fill );
			$this->fpdf->Cell( 15, 7, $detail->jumlah, 1, 0, 'C', $fill );
			$this->fpdf->Cell( 70, 7, $detail->item_name, 1, 0, 'L', $fill );
			$this->fpdf->Cell( 25, 7, $detail->item_group_name, 1, 0, 'L', $fill );
			$this->fpdf->Cell( 25, 7, number_format($harga, 2, "," , "."), 1, 0, 'R', $fill );
			$this->fpdf->Cell( 25, 7, number_format($harga * $jumlah, 2, "," , "."), 1, 0, 'R', $fill );
			$this->fpdf->Ln( 7 );
			$subtotal += ($harga*$jumlah);
		}

		// subtotal
		$this->fpdf->SetX(150);
		$this->fpdf->SetTextColor( $tableHeaderTopTextColour[0], $tableHeaderTopTextColour[1], $tableHeaderTopTextColour[2] );
		$this->fpdf->SetFillColor( $tableHeaderTopFillColour[0], $tableHeaderTopFillColour[1], $tableHeaderTopFillColour[2] );
		$this->fpdf->SetFont( 'Arial', 'B', 8 );
		$this->fpdf->Cell( 25, 8, "Subtotal :", 1, 0, 'C', true );
		
		$this->fpdf->SetFont( 'Arial', '', 8 );
		$this->fpdf->SetTextColor( $textColour[0], $textColour[1], $textColour[2] );
		$this->fpdf->SetFillColor( $tableRowFillColour[0], $tableRowFillColour[1], $tableRowFillColour[2] );
		$this->fpdf->Cell( 25, 8, number_format($subtotal, 2, "," , "."), 1, 0, 'R', $fill );

		if ($this->fpdf->GetY() >= 267) {
			$this->fpdf->SetY(-15); 
			$this->fpdf->Cell(0, 8, "~~ Printed by " . $this->session->userdata('username') . " ~~", 0, 0, 'C' );
			//Arial italic 8 

			$this->fpdf->SetFont('Arial','I',8); 
			$this->fpdf->Cell(10,8,'Page '.$this->fpdf->PageNo().'/{nb}',0,0,'R'); 
	
		}
		
		//$this->fpdf->Cell(160,-5,"Delivery Notes",0,1,'R');	
		

		
		//Signature of Person Handling Over
		//Signature of Recipient
		
		// get nik name from sales and current user login
		$userID = $scan_in->user_id;
		$recipient = $this->mscan->getNikName($userID);
		$handler = $this->mscan->getNikName($this->session->userdata('username'));
		
		// signature field
		$this->fpdf->Ln( 30 );
		$this->fpdf->SetTextColor( $tableHeaderTopTextColour[0], $tableHeaderTopTextColour[1], $tableHeaderTopTextColour[2] );
		$this->fpdf->SetFillColor( $tableHeaderTopFillColour[0], $tableHeaderTopFillColour[1], $tableHeaderTopFillColour[2] );
		$this->fpdf->SetFont( 'Arial', 'B', 8 );
		$this->fpdf->Cell( 55, 12, "Signature of Person Handling Over:", 1, 0, 'L', true );
		
		 
		$this->fpdf->SetFont( 'Arial', '', 8 );
		$this->fpdf->SetTextColor( $textColour[0], $textColour[1], $textColour[2] );
		$this->fpdf->SetFillColor( $tableRowFillColour[0], $tableRowFillColour[1], $tableRowFillColour[2] );
		$this->fpdf->Cell( 60, 12, $handler, 1, 0, 'L', $fill );
		$this->fpdf->Cell( 40, 12, "", 1, 0, 'L', $fill );
		
		$this->fpdf->Ln( 12 );
		$this->fpdf->SetTextColor( $tableHeaderTopTextColour[0], $tableHeaderTopTextColour[1], $tableHeaderTopTextColour[2] );
		$this->fpdf->SetFillColor( $tableHeaderTopFillColour[0], $tableHeaderTopFillColour[1], $tableHeaderTopFillColour[2] );
		$this->fpdf->SetFont( 'Arial', 'B', 8 );
		$this->fpdf->Cell( 55, 12, "Signature of Recipient:", 1, 0, 'L', true );	
		
		$this->fpdf->SetFont( 'Arial', '', 8 );
		$this->fpdf->SetTextColor( $textColour[0], $textColour[1], $textColour[2] );
		$this->fpdf->SetFillColor( $tableRowFillColour[0], $tableRowFillColour[1], $tableRowFillColour[2] );
		$this->fpdf->Cell( 60, 12, $recipient, 1, 0, 'L', $fill );
		$this->fpdf->Cell( 40, 12, "", 1, 0, 'L', $fill );
		
		
		//Position at 1.5 cm from bottom 
		$this->fpdf->SetY(-15); 
		$this->fpdf->Cell(0, 8, "~~ Printed by " . $this->session->userdata('username') . " ~~", 0, 0, 'C' );
		$this->fpdf->SetFont('Arial','I',8); 
		//Page number 
		$this->fpdf->Cell(10,8,'Page '.$this->fpdf->PageNo().'/{nb}',0,0,'R'); 
		$this->fpdf->Output();
	
	}

	
	public function credit_limit($sales_id='')
	{
		$data['template'] = "shell/smooth";
		$data['territory'] = $this->mscan->getClusterName($this->session->userdata("username"));

		if ($sales_id) {

			//20120719 ayu decode id sales
			$sales_id = $this->enc->defog($sales_id);
			$data['main_view'] = "f-credit-limit";
			$data['sales'] = $this->mscan->get_sales( $this->session->userdata("username") );
			$data['sales_detail'] = $this->credit_limit_user($sales_id);
		}
		else {
			$data['main_view'] = "grid-credit-limit";
			// get all credit limit of sales on current territory
			/*$data['sales'] = $this->mscan->get_all_credit_limit($this->session->userdata("username"));*/
			//20120719 ayu
			$result = $this->mscan->get_all_credit_limit($this->session->userdata("username"));

	        //encode
	        for($i=0;$i<count($result);$i++){
	        	$result[$i]->nomor = $i+1; 
	    		$result[$i]->custom_user_id = $this->enc->fogit($result[$i]->user_id);
	    	}
	        
	        $data['sales'] = $result;
	    }

		$this->load->view($data['template'], $data);
	}

	function credit_limit_user($sales_id='', $p='')
	{
		if ($sales_id) {
			$data['credit_limit'] = $this->mscan->credit_limit($sales_id); // get the latest credit limit of current sales
			$data['history'] = $this->mscan->credit_limit_history($sales_id);
			if ($p) {
				echo json_encode($data);
			}
			else 
			{
				return $data;
			}
			// return ;
		}
		else {
			redirect('index.php/scan/credit_limit');
		}

	}

	function save_credit_limit($sales_id) { 
		$new_limit = $this->input->post("limit");
		$remark = $this->input->post("remark");

		$new_limit = $this->mscan->save_new_limit($sales_id, $new_limit, $remark);

		if ($new_limit) {
			echo json_encode(array('user_id'=> $sales_id, 'status'=>"Success"));
		}

	}
	
}